package com.wanlian.router.ui.integral.intc;

import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.InputFilter;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.smart.android.ui.BaseActivity;
import com.smart.android.ui.web.WebActivity;
import com.smart.android.widget.EditTextWithClear;
import com.wanlian.router.GlobalInfo;
import com.wanlian.router.R;
import com.wanlian.router.app.AppConfig;
import com.wanlian.router.bean.IntegralTotal;
import com.wanlian.router.net.NetWorkingClient;
import com.wanlian.router.net.ResponseData;
import com.wanlian.router.net.internal.INetCallBack;
import com.wanlian.router.storage.AppData;
import com.wanlian.router.ui.main.yun.InputDialog;

import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Hyu on 2018/9/4.
 * Email: fvaryu@163.com
 */
public class TransferINTActivity extends BaseActivity implements TextWatcher {

    @BindView(R.id.tv_score)
    TextView tv_score;
    @BindView(R.id.tv_rule)
    TextView tv_rule;

    @BindView(R.id.ll_account)
    LinearLayout ll_account;
    @BindView(R.id.tv_create)
    TextView tv_create;
    @BindView(R.id.tv_bind)
    TextView tv_bind;
    @BindView(R.id.tv_tip)
    TextView tv_tip;
    @BindView(R.id.tv_max)
    TextView tv_max;

    @BindView(R.id.et_address)
    EditTextWithClear et_address;
    @BindView(R.id.et_amount)
    EditTextWithClear et_amount;

    @BindView(R.id.tv_next)
    TextView tv_next;

    private static final int DECIMAL_DIGITS = 6;

    private InputFilter lengthFilter = new InputFilter() {

        @Override
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            // source:当前输入的字符
            // start:输入字符的开始位置
            // end:输入字符的结束位置
            // dest：当前已显示的内容
            // dstart:当前光标开始位置
            // dent:当前光标结束位置
            Log.i("", "source=" + source + ",start=" + start + ",end=" + end
                    + ",dest=" + dest.toString() + ",dstart=" + dstart
                    + ",dend=" + dend);
            if (dest.length() == 0 && source.equals(".")) {
                return "0.";
            }
            String dValue = dest.toString();
            String[] splitArray = dValue.split("\\.");
            if (splitArray.length > 1) {
                String dotValue = splitArray[1];
                if (dotValue.length() == DECIMAL_DIGITS) {
                    return "";
                }
            }
            return null;
        }

    };


    @Override
    protected int layout() {
        return R.layout.activity_transfer_int;
    }

    @Override
    public void initUI() {
        super.initUI();
        setTitle("提取INT积分");

        tv_rule.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        tv_create.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
    }

    @Override
    public void initData() {
        super.initData();

        et_amount.addTextChangedListener(this);
        et_address.addTextChangedListener(this);

        et_amount.setFilters(new InputFilter[] { lengthFilter });


        load();
    }

    private void load() {
        if (TextUtils.isEmpty(GlobalInfo.getInstance().getUser().getIntAccount())) {
            et_address.setVisibility(View.GONE);
            ll_account.setVisibility(View.GONE);
            tv_tip.setVisibility(View.VISIBLE);
            tv_create.setVisibility(View.VISIBLE);
            tv_bind.setTextColor(getColorById(R.color.color_blue));
            tv_bind.setBackgroundResource(R.drawable.drawable_bg_white_blue_5);
            tv_bind.setText("绑定以太坊钱包");

        } else {
            et_address.setFocusable(false);
            et_address.setClickable(false);
            et_address.setEnabled(false);
            et_address.setText(GlobalInfo.getInstance().getUser().getIntAccount());
            et_address.setVisibility(View.VISIBLE);
            ll_account.setVisibility(View.VISIBLE);
            tv_tip.setVisibility(View.GONE);
            tv_create.setVisibility(View.GONE);
            tv_bind.setTextColor(getColorById(R.color.color_99));
            tv_bind.setBackgroundResource(R.drawable.drawable_bg_white_gray_5);
            tv_bind.setText("解绑以太坊钱包");
        }

        NetWorkingClient.getInstance().queryIntegral(getActivity(), 0, new INetCallBack<List<IntegralTotal>>() {
            @Override
            public void onFinish(ResponseData response, @Nullable List<IntegralTotal> integralTotals) {
                if (response.isSuccess()) {

                    if (integralTotals != null && integralTotals.size() > 0) {
                        IntegralTotal integralTotal = integralTotals.get(0);

                        SpannableString ss = new SpannableString(String.format(Locale.getDefault(), "您当前可提取的积分额度为：%f积分", integralTotal.getIscore()));
                        ss.setSpan(new ForegroundColorSpan(getColorById(R.color.color_blue)), 13, ss.length() - 2, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
                        tv_score.setText(ss);

                        if (ss.length() > 25) {
                            tv_score.setEllipsize(TextUtils.TruncateAt.MARQUEE);
                            tv_score.setSingleLine(true);
                            tv_score.setSelected(true);
                            tv_score.setFocusable(true);
                            tv_score.setFocusableInTouchMode(true);
                        }


                        tv_max.setText(String.format(Locale.getDefault(), "(最大可提取%.6f个INT)", integralTotal.getIntnum()));
                    }
                } else {
                    showToast(response.getMessage());
                }
            }
        });
    }


    @OnClick(R.id.tv_bind)
    void bind(View view) {

        if (TextUtils.isEmpty(GlobalInfo.getInstance().getUser().getIntAccount())) {
            InputDialog dialog = new InputDialog(getActivity());
            dialog.setTitle("绑定以太坊钱包");
            dialog.setHidden("请输入以太坊钱包");
            dialog.setOnNameInputListener(new InputDialog.OnNameInputListener() {
                @Override
                public void onNameInput(Dialog dialog, final String name) {
                    dialog.dismiss();
                    NetWorkingClient.getInstance().bindINTAccount(getActivity(), name, new INetCallBack() {
                        @Override
                        public void onFinish(ResponseData response, @Nullable Object o) {
                            if (response.isSuccess()) {
                                GlobalInfo.getInstance().getUser().setIntAccount(name);
                                showToast("绑定成功");
                                load();
                            } else {
                                showToast(response.getMessage());
                            }
                        }
                    });
                }
            });
            dialog.show();
        } else {
            new AlertDialog.Builder(getActivity())
                    .setMessage("确定解绑吗？")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            NetWorkingClient.getInstance().unbindINTAccount(getActivity(), new INetCallBack() {
                                @Override
                                public void onFinish(ResponseData response, @Nullable Object o) {

                                    if (response.isSuccess()) {

                                        GlobalInfo.getInstance().getUser().setIntAccount(null);
                                        showToast("解绑成功");
                                        load();
                                    } else {
                                        showToast(response.getMessage());
                                    }
                                }
                            });
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create().show();

        }


    }

    @OnClick(R.id.tv_create)
    void create() {
        WebActivity.fire(getActivity(), AppData.DEFAULT.get(AppConfig.CREATE_INT));
    }

    @OnClick(R.id.tv_rule)
    void rule() {
        WebActivity.fire(getActivity(), AppData.DEFAULT.get(AppConfig.INT_GETROLE));
    }


    @OnClick(R.id.tv_next)
    void next() {
        String a = et_amount.getText().toString();

        double amount = 0f;
        try {
            amount = Double.parseDouble(a);
        } catch (NumberFormatException e) {
            showToast("输入有误");
            return;
        }
        if (amount < 1000) {
            showToast("最少1000个起兑");
            return;
        }
        NetWorkingClient.getInstance().exchangeINT(getActivity(), amount, new INetCallBack() {
            @Override
            public void onFinish(ResponseData response, @Nullable Object o) {
                if (response.isSuccess()) {
                    showToast("兑换成功");
                    load();
                } else {
                    showToast(response.getMessage());
                }
            }
        });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

        tv_next.setEnabled(et_address.getText() != null && !TextUtils.isEmpty(et_address.getText().toString()) &&
                et_amount.getText() != null && !TextUtils.isEmpty(et_amount.getText().toString())
        );
    }
}
